package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private Socket socket;
    //状态行
    private int statusCode=200;
    private String statusReason="OK";
    private Map<String,String> headers=new HashMap<>();
    private File contentFile;

    public HttpServletResponse(Socket socket){
        this.socket=socket;
    }

    public void response() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    private void sendContent() throws IOException {
        OutputStream out=socket.getOutputStream();
        FileInputStream fis=new FileInputStream(contentFile);
        byte[] bytes=new byte[1024*10];
        int len;
        while ((len=fis.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
    }

    private void sendStatusLine() throws IOException {
        println("HTTP/1.1 "+statusCode+" "+statusReason);
    }

    private void sendHeaders() throws IOException {
        Set<Map.Entry<String,String>> entry=headers.entrySet();
        for (Map.Entry<String,String> e:entry){
            String key=e.getKey();
            String value=e.getValue();
            println(key+": "+value);
        }
        println("");//响应头最后会发送一个单独的回车和换行
    }

    private void println(String line) throws IOException {
        OutputStream out=socket.getOutputStream();
        byte[] bytes=line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(bytes);
        out.write(13);
        out.write(10);

    }
    public void addHeader(String key,String value){
        headers.put(key, value);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        String contentType=null;
        try {
            contentType= Files.probeContentType(contentFile.toPath());//转路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (contentType!=null){
            addHeader("Content-Type",contentType);
        }
        addHeader("Content-Length",contentFile.length()+"");

    }
}
